import { resolveApp } from "./path";
import fs from "fs-extra";
import shell from "shelljs";

enum FileType {
  Typescrit,
  Html,
}

if (!process.argv[2]) {
  throw new Error(
    "请输入组件名称：组件名称类似，比如输入 home/index,会在 home/index/index.view.html 和 home/index/index.view.ts",
  );
}

//读取模板中的文本内容
const tsContent = fs.readFileSync(resolveApp("template/index.ts")).toString();
const htmlContent = fs
  .readFileSync(resolveApp("template/index.html"))
  .toString();
createFileFillContent(FileType.Html, htmlContent);
createFileFillContent(FileType.Typescrit, tsContent);
addGitCatch();

function addGitCatch() {
  // 把新创建的文件加到 git 暂缓
  shell.exec("git add .", (code: number, stdout: string, stderr: string) => {
    if (code === 0) {
      console.log("执行成功 !!!", stdout);
    } else {
      console.log("git add 失败！", stderr);
    }
  });
}

// 创建文件并把模板中的内容写到新创建的文档中去
function createFileFillContent(fileType: FileType, content: string) {
  const pathName = process.argv[2];
  const path = resolveApp("src/pages/" + pathName);
  const namePrefix = pathName.substring(pathName.lastIndexOf("/") + 1);

  if (!fs.existsSync(path)) {
    fs.ensureDirSync(path);
  }

  const fileName =
    fileType === FileType.Html
      ? path + "/" + namePrefix + ".view.html"
      : path + "/" + namePrefix + ".view.ts";

  if (!fs.existsSync(fileName)) {
    fs.ensureFileSync(fileName);
    fs.writeFileSync(fileName, content);
  } else {
    throw new Error("文件已存在，请重新命名！");
  }
}
